package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("用户下单成功");
    }

    /**
     * 移动端历史订单
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){
        Page page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getCheckoutTime);
        ordersService.page(page1,lqw);

        Page page2 = new Page();
        BeanUtils.copyProperties(page1,page2,"records");
        List<Orders> records = page1.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        records.forEach(s->{
            Long id = s.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,id);
            List<OrderDetail> list = orderDetailService.list(queryWrapper);

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(s,ordersDto);
            ordersDto.setOrderDetails(list);
            ordersDtos.add(ordersDto);
        });
        page2.setRecords(ordersDtos);

        return R.success(page2);
    }

    /**
     * 客户端查看订单明细
     * @param page
     * @param pageSize
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){
        Page page1 = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getOrderTime);
        lqw.like(number!=null,Orders::getNumber,number);
        lqw.between(beginTime!=null&&endTime!=null,Orders::getOrderTime,beginTime,endTime);
        ordersService.page(page1,lqw);
        return R.success(page1);
    }

    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        ordersService.updateById(orders);
        return R.success("修改状态成功");
    }


}
